package com.example.fuluchou.common.untils;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Collection;
import java.util.concurrent.TimeUnit;

@Slf4j
@Configuration
public class RedisUtil {
    private static Logger logger = LoggerFactory.getLogger(RedisUtil.class);

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 添加
     */
    public boolean set(String key, String value) {
        try {
            redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            logger.error("RedisUtil error: set{},{}", key, value, e);
            return false;
        }

    }

    /**
     * 添加,附带过期时间
     */
    public boolean set(String key, String value, long time) {
        try {
            redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
            return true;
        } catch (Exception e) {
            logger.error("RedisUtil error: setex{},{},{}", key, value, time, e);
            return false;
        }

    }

    /**
     * 获取指定key的value
     */
    public String get(String key) {
        try {
            if (StringUtils.hasText(key)) {
                 return redisTemplate.opsForValue().get(key);
            }
            return null;

        }catch (Exception e) {
            logger.error("RedisUtil error: get{}",key,e);
            return null;
        }
    }

    /**
     * 删除key
     */
    public boolean del(String... key) {
        try {
            if(key != null & key.length > 0) {
                if(key.length == 1) {
                    redisTemplate.delete(key[0]);
                }else  {
                    redisTemplate.delete((Collection<String>) CollectionUtils.arrayToList(key));
                }
            }
            return false;

        }catch (Exception e){
            logger.error("RedisUtil error: del{}",key,e);
            return false;
        }
    }

    /**
     * 检查key是否存在
     */
    public boolean hasKey(String key) {
        try {
            if(StringUtils.hasText(key)) {
                return redisTemplate.hasKey(key);
            }
            return false;
        }catch (Exception e){
            logger.error("RedisUtil error: hasKey{}",key,e);
            return false;
        }
    }
}
